package util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.ArrayList;

/**
 * Obtener el hash sha1 de una cadena
 * @author marvil
 */
public class Logica {

    public static String hashDeCadena(String cadena) {
        try {
            byte[] bytesDeCadena = cadena.getBytes(); // charset opcional
            // sha1: 20 bytes(40 digitos hexademimales)
            MessageDigest md = MessageDigest.getInstance("sha-1");
            md.update(bytesDeCadena);
            byte[] digest = md.digest();
            StringBuffer buf = new StringBuffer();
            for (byte b: digest) {
                //TODO: revisar salida
                buf.append(String.format("%02x", b & 0xFF));
            }
            System.out.println(">> " + cadena);
            System.out.println(">> " + buf.toString());
            return buf.toString();
        //} catch (UnsupportedEncodingException ex) { // solo si charset especifico
        //    Logger.getLogger(Logica.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Logica.class.getName()).log(Level.SEVERE, null, ex);
        }
        return "";
    }

    public static String hashDeArreglo(ArrayList datos) {
        StringBuffer buf = new StringBuffer();
        for (Object o: datos) {
            buf.append(o.toString());
        }
        //incluir una llave externa simple
        return Logica.hashDeCadena(buf.toString() + "llave");
    }
}
